package com.example.demo.filter;

import com.example.demo.entity.Admin;
import com.example.demo.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter init。。。。。。");
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter destroy。。。。。。");
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest hsr=(HttpServletRequest)servletRequest;
        HttpServletResponse hsrp=(HttpServletResponse)servletResponse;

        String contextPath = hsr.getContextPath();
        String requestURI = hsr.getRequestURI();
        System.out.println("过滤器Filter测试执行…………");
        if(requestURI.contains("register")
                ||requestURI.contains("login")||requestURI.contains("css")||requestURI.contains("js")){
//            不过滤的url,直接放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            Object attribute = hsr.getSession().getAttribute("user");
            Object attribute2 = hsr.getSession().getAttribute("admin");
            if(attribute!=null){
                System.out.println(attribute);
//                已经登录
                filterChain.doFilter(servletRequest,servletResponse);
            }else if (attribute2!=null){
                //管理员已经登陆
                System.out.println(attribute2);
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
//                没有登录，跳转到登录页面
                hsrp.sendRedirect("/user/loginpage");
            }
        }
    }

}

